package com.x.erp.manage;

import com.x.erp.dao.InsuranceGoodsVoucherDao;
import com.x.erp.dao.InsuranceOrderDao;
import com.x.erp.model.InsuranceGoodsVoucher;
import com.x.erp.model.InsuranceOrder;
import com.x.erp.util.ConstantState;
import com.x.framework.manage.BaseManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class InsuranceGoodsVoucherManage extends BaseManage {

	@Autowired
	private InsuranceGoodsVoucherDao insuranceGoodsVoucherDao;

	/**
	 * 修改多条使用券（核销）
	 *
	 * @param insuranceGoodsVouchers
	 * @return
	 */
	public int updateVoucherList(InsuranceOrder insuranceOrder, List<InsuranceGoodsVoucher> insuranceGoodsVouchers) throws Exception {
		int tem = 0;
		for (InsuranceGoodsVoucher insuranceGoodsVoucher : insuranceGoodsVouchers) {
			Date cDate = new Date();
			insuranceGoodsVoucher.setVoucherVerificationTime(cDate);
			insuranceGoodsVoucher.setVoucherUpdateTime(cDate);
			insuranceGoodsVoucher.setVoucherVerificationState(ConstantState.INSURANCE_VERIFICATION_STATE_VERIFICATED);
			int res = this.update(insuranceGoodsVoucher);
			tem += res;
		}
		// 查看该订单的商品使用券是否都已核销，如果都核销修改订单状态为已完成
		changeOrderState(insuranceOrder);
		return tem;
	}

	// 查看该订单的商品使用券是否都已核销，如果都核销修改订单状态为已完成
	private void changeOrderState(InsuranceOrder insuranceOrder) throws Exception {
		InsuranceGoodsVoucher insuranceGoodsVoucher = new InsuranceGoodsVoucher();
		insuranceGoodsVoucher.setOrderId(insuranceOrder.getOrderId());
		// 查询该订单未核销的使用券
		insuranceGoodsVoucher.setVoucherVerificationState(ConstantState.INSURANCE_VERIFICATION_STATE_INITIAL);
		List<InsuranceGoodsVoucher> list = insuranceGoodsVoucherDao.selectVoucherList(insuranceGoodsVoucher);
		// 如果全部已核销，修改订单状态为已完成
		if(list == null || list.size() == 0){
			insuranceOrder.setOrderState(ConstantState.INSURANCE_ORDER_STATE_FINISH);
			insuranceOrder.setOrderUpdateTime(new Date());
			this.update(insuranceOrder);
		}
	}
}
